#!/usr/bin/env node
var jse = require('./jse.js').$jse;
var argv = require('./lib/optimist.js')
	.string('input')
	.string('output')
	.boolean('pretty')
	.demand(['input', 'output'])
	.argv;


var fs = require('fs');
var path = require('path');

var input = path.normalize(argv.input);
var output = path.normalize(argv.output);

console.log('Reading file...');
var uncompiled = fs.readFileSync(input, 'utf8');
console.log('Compiling...');
var compiled = jse.compile(uncompiled);

fs.writeFileSync(output+'.tmp', compiled, 'utf8');

console.log('Calling Closure Compiler...');

var compilationLevel = '';
if(argv.pretty){
	compilationLevel = '--formatting PRETTY_PRINT --compilation_level WHITESPACE_ONLY';
}

var closureCompiler = require('child_process').exec('java -jar '+path.join(__dirname, 'closure_compiler.jar')+' '+compilationLevel+' --warning_level VERBOSE --jscomp_off=uselessCode --jscomp_off=checkTypes --js_output_file "'+output+'"');
var closureHadError = false;

closureCompiler.stderr.on('data', function(data){
	process.stderr.write(data);
	closureHadError = true;
});

closureCompiler.stdout.on('data', function(data){
	process.stdout.write(data);
	closureHadError = true;
});

closureCompiler.stdin.write(compiled);
closureCompiler.stdin.end();

if(!closureHadError){
	//fs.unlinkSync(output+'.tmp')
}